package leetcode.code322;

import java.util.Arrays;

/**
 * 超时
 *
 * @author CaoYu
 * @date 2021年9月14日
 * @description
 */
public class Solution1 extends Solution322 {

	@Override
	public int coinChange(int[] coins, int amount) {
		if (amount == 0)
			return 0;
		Arrays.sort(coins);
		int[][] cache = new int[coins.length][amount + 1];
		return this.coinChange(coins, amount, coins.length - 1, cache);
	}

	private int coinChange(int[] coins, int amount, int index, int[][] cache) {
		if (amount == 0)
			return 0;
		if (index == -1)
			return -1;
		if (cache[index][amount] != 0) {
			return cache[index][amount];
		}
		int ans = Integer.MAX_VALUE;
		for (int i = index; i >= 0; i--) {
			int num = amount / coins[i];
			while (num >= 0) {
				int left = amount - num * coins[i];
				int res = coinChange(coins, left, i - 1, cache);
				if (res != -1) {
					ans = Math.min(ans, res + num);
				}
				num--;
			}
		}
		return ans == Integer.MAX_VALUE ? -1 : ans;
	}

	public static void main(String[] args) {
		Solution1 so = new Solution1();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
		so.debug5();
		so.debug6();
		so.debug7();
		so.debug8();
	}

}
